package net.wicp.tams.common.apiext.json.serializerconfig;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;

import com.alibaba.fastjson.serializer.DoubleSerializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

/***
 * Double格式保留两位小数点（0.00）
 * 
 * @author Administrator
 *
 */
public class DoubleSerializerConfig extends DoubleSerializer {
	public DoubleSerializerConfig(DecimalFormat decimalFormat) {
		this.decimalFormat = decimalFormat;
	}

	private DecimalFormat decimalFormat = null;

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
			throws IOException {
		SerializeWriter out = serializer.out;

		if (object == null) {
			out.writeNull(SerializerFeature.WriteNullNumberAsZero);
			return;
		}
		double doubleValue = ((Double) object).doubleValue();
		if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
			out.writeNull();
		} else {
			if (decimalFormat == null) {
				out.writeDouble(doubleValue, true);
			} else {
				String doubleText = decimalFormat.format(doubleValue);
				out.write("\"" + doubleText + "\"");
			}
		}
	}
}